package com.zzptc.myapp1112;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zzptc.myapp1112.Bean.User;

import org.litepal.LitePal;

import java.util.IllegalFormatCodePointException;
import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private EditText usnedit,psdedit;
    private Button  loginbtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getUser();
        initView();
        setListener();

    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn = usnedit.getText().toString().trim();
                String psd = psdedit.getText().toString().trim();
                User user = confirmUser(usn, psd);
                if (user == null) {
                    //登录失败
                } else {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("myid", user.getId());
                    editor.putString("myname", user.getName());
                    editor.apply();
                    startActivity(intent);
                }

            }
        });

    }
    private User confirmUser(String usn,String psd){
        List<User>userList= LitePal.findAll(User.class);
        for(User u:userList){
            if (usn.equals(u.getName())&&psd.equals(u.getPassword())){



                return u;
            }
        }
        return null;
    }





    private void getUser() {
        User user = new User(0,"张三","123");
        User user1 = new User(0,"李四","456");
        User user2 = new User(0,"王五","789");
        User user3 = new User(0,"赵六","123456");

        user.save();
        user1.save();
        user2.save();
        user3.save();


    }


    private void initView() {
        usnedit=findViewById(R.id.usnedit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);


    }
}
